package com.dankegongyu.lib.common.util;

import android.net.Uri;
import android.text.TextUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wupuquan
 * @version 1.0
 * @since 2017/12/12 14:20
 */
public class DKUrlUtil {

    private DKUrlUtil() {
        throw new AssertionError("cannot be instantiated");
    }

    public static String getQueryParameter(Uri uri, String key) {
        if (uri == null || TextUtils.isEmpty(key)) {
            return "";
        }
        String value = uri.getQueryParameter(key);
        return TextUtils.isEmpty(value) ? "" : value;
    }

    public static Map<String, String> getUrlParams(String url) {
        Map<String, String> map = new HashMap<>();
        if (url == null || url.trim().length() == 0) {
            return map;
        }

        try {
            url = URLDecoder.decode(url, "UTF-8");
            int index = url.indexOf("?");
            if (index < 0) {
                return map;
            }

            String args = url.substring(index + 1); // 从?往前都截取
            String[] argArray = args.split("&");
            for (String arg : argArray) {
                String[] params = arg.split("=");
                map.put(params[0], params[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    public static String encodeUTF8(String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (Throwable e) {
            return "";
        }
    }

    public static String encode(String s, String enc) {
        try {
            return URLEncoder.encode(s, enc);
        } catch (Throwable e) {
            return "";
        }
    }

    public static String decodeUTF8(String s) {
        try {
            return URLDecoder.decode(s, "UTF-8");
        } catch (Throwable e) {
            return "";
        }
    }

    public static String decode(String s, String enc) {
        try {
            return URLDecoder.decode(s, enc);
        } catch (Throwable e) {
            return "";
        }
    }
}
